package com.fdb.efp.console.api.rest;

import com.fdb.basic.framework.core.constant.DataRuleType;
import com.fdb.basic.framework.core.constant.PubConstant;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.web.controller.AbstractController;
import com.fdb.efp.console.service.facade.SRoleService;
import com.fdb.efp.console.service.vo.SRoleVO;
import com.fdb.efp.console.service.facade.SRoleDataRuleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class SRoleController extends AbstractController {

    @Autowired
    @Qualifier("sRoleService")
    private SRoleService sRoleService;
    @Autowired
    @Qualifier("sRoleDataRuleService")
    private SRoleDataRuleService sRoleDataRuleService;

    /**
     * 列表数据查询
     *
     * @param vo
     * @return
     */
    @RequestMapping(value = "/s/roles", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<SRoleVO>> querySRoleAll(@RequestBody SRoleVO vo) {
        List<SRoleVO> outputVo = null;
        // 根据用户角色获取用户权限方案
        Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
        vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
        setUserInfoToVO(vo);
        // 根据权限方案调用不同的方案进行数据查询
        switch (dataRuleType) {
            case Owner:
                outputVo = sRoleService.queryAllOwner(vo);
                break;
            case CurrOrg:
                outputVo = sRoleService.queryAllCurrOrg(vo);
                break;
            case CurrDownOrg:
                outputVo = sRoleService.queryAllCurrDownOrg(vo);
                break;
            default:
                outputVo = sRoleService.queryAllOwner(vo);
                break;
        }
        return getResponseData(outputVo);

    }

    /**
     * 根据主键查询详情
     *
     * @return
     */
    @RequestMapping(value = "/s/role/{roleCode}", method = RequestMethod.GET)
    public @ResponseBody
    ResponseData<SRoleVO> queryByPk(@PathVariable("roleCode") String roleCode) {
        SRoleVO inVo = new SRoleVO();
        inVo.setRoleCode(roleCode);
        SRoleVO outputVo = sRoleService.queryByPk(inVo);
        return getResponseData(outputVo);

    }

    /**
     * 根据主键删除信息
     *
     * @param sRole
     * @return
     */
    @RequestMapping(value = "/s/role", method = RequestMethod.DELETE)
    public @ResponseBody
    ResponseData<Integer> deleteByPk(@RequestBody SRoleVO inSRoleVo) {
        int outputVo = sRoleService.deleteByPk(inSRoleVo);
        return getResponseData(outputVo);

    }

    /**
     * 根据主键更新信息
     *
     * @param inSRoleVo
     * @return
     */
    @RequestMapping(value = "/s/role", method = RequestMethod.PUT)
    public @ResponseBody
    ResponseData<Integer> updateByPk(@RequestBody SRoleVO inSRoleVo) {
        setUserInfoToVO(inSRoleVo);
        List<SRoleVO> sRoleVOS = sRoleService.queryAllByCoditions(inSRoleVo);
        if(Objects.nonNull(sRoleVOS) && sRoleVOS.size() > 0){
            int result = sRoleVOS.stream()
                    .filter(sRoleVO -> {
                        return !StringUtils.equals(inSRoleVo.getRoleCode(), sRoleVO.getRoleCode());
                    })
                    .collect(Collectors.toList())
                    .size();
            if (result > 0)
                return getResponseData(-11);
        }
        int outputVo = sRoleService.updateByPk(inSRoleVo);
        return getResponseData(outputVo);

    }

    /**
     * 新增数据
     *
     * @param inSRoleVo
     * @return
     */
    @RequestMapping(value = "/s/role", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<Integer> insertSRole(@RequestBody SRoleVO inSRoleVo) {
        setUserInfoToVO(inSRoleVo);
        /**
         * 【2019D0519】【(问题编号)】 判断角色是否重复
         * 【解决方案】 判断角色名称（精确匹配）是否在新增的适用机构，或其上下级机构存在。若存在，则为重复
         */
        //获取适用机构关联的上下级机构信息
       /** List<SOrgVO> sOrgVOList = sOrgService.queryAllByOrgCode(inSRoleVo.getOrgCode());
        if(Objects.nonNull(sOrgVOList)){
            List<String> locationList = sOrgVOList.stream()
                    .map(SOrgVO::getLocation)
                    .collect(Collectors.toList());
            //转为字符串并去重
            String orgLocation = this.getOrgLocations(locationList);
            if(StringUtil.isStrNotEmpty(orgLocation)){
                inSRoleVo.setOrgsLocation(orgLocation);
                List<SRoleVO> sRoleVOList = sRoleService.queryAllByOrgs(inSRoleVo);
                if(Objects.nonNull(sRoleVOList) && sRoleVOList.size() > 0){
                    return getResponseData(-11);
                }
            }
        }*/
        List<SRoleVO> sRoleVOS = sRoleService.queryAllByCoditions(inSRoleVo);
        if(Objects.nonNull(sRoleVOS) && sRoleVOS.size() > 0){
            return getResponseData(-11);
        }
        int outputVo = sRoleService.insertSRole(inSRoleVo);
        return getResponseData(outputVo);
    }

    /**
     * 查询角色是否绑定
     *
     * @param inSRoleVo
     * @return
     */
    @RequestMapping(value = "/s/role/bind/user", method = RequestMethod.POST)
    public @ResponseBody ResponseData<Integer> queryRoleBindUser(@RequestBody SRoleVO inSRoleVo) {
        setUserInfoToVO(inSRoleVo);
        int outputVo = sRoleService.queryRoleBindUserTotal(inSRoleVo);
        return getResponseData(outputVo);
    }

    /**
     * 查询生效的当前登录用户所属机构及下属机构的所有角色数据
     *
     * @return
     */
    @RequestMapping(value = "/s/queryRoleAll", method = RequestMethod.POST)
    public @ResponseBody ResponseData<List<SRoleVO>> queryRoleAll(@RequestBody SRoleVO sRoleVo) {
        setUserInfoToVO(sRoleVo);
        List<SRoleVO> outputVo = sRoleService.queryRoleAll(sRoleVo);
        return getResponseData(outputVo);
    }

    @RequestMapping(value = "/s/role/legal/status", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<SRoleVO>> queryRoleByLcAndStByPage(@RequestBody SRoleVO sRoleVo) {
        setUserInfoToVO(sRoleVo);
        List<SRoleVO> outputVo = sRoleService.queryRoleByLcAndStByPage(sRoleVo);
        return getResponseData(outputVo);

    }

    /**
     * 查询当前登录用户机构的所有角色
     *
     * @return
     */
    @RequestMapping(value = "/s/roles/leage/code", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<SRoleVO>> queryRoleAllByLoginLeage(@RequestBody SRoleVO sRoleVo) {
        setUserInfoToVO(sRoleVo); //设置当前登录用户信息
        List<SRoleVO> outputVo = sRoleService.queryRoleAllByLoginLeage(sRoleVo);

        return getResponseData(outputVo);
    }

    /**
     * 角色下用户列表数据查询
     *
     * @return
     */
    @RequestMapping(value = "/s/roles/user", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<SRoleVO>> queryRoleUserAll(@RequestBody SRoleVO sRoleVo) {
        List<SRoleVO> outputVo = sRoleService.queryRoleUserAll(sRoleVo);
        return getResponseData(outputVo);
    }

    /**
     * 不分页权限控制查询角色数据
     *
     * @param sRoleVo
     * @return
     * @author qiuyf
     * @version 1.0
     * @since 2019年2月14日 下午8:24:04
     */
    @RequestMapping(value = "/s/queryRolesCtrl", method = RequestMethod.POST)
    public @ResponseBody
    ResponseData<List<SRoleVO>> queryRolesCtrl(@RequestBody SRoleVO sRoleVo) {
        List<SRoleVO> outputVo = null;
        // 根据用户角色获取用户权限方案
        Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
        sRoleVo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get("prd_code"));
        DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get("permis_type"));
        setUserInfoToVO(sRoleVo);
        // 根据权限方案调用不同的方案进行数据查询
        switch (dataRuleType) {
            case Owner:
                outputVo = sRoleService.queryAllOwnerNotPage(sRoleVo);
                break;
            case CurrOrg:
                outputVo = sRoleService.queryAllCurrOrgNotPage(sRoleVo);
                break;
            case CurrDownOrg:
                outputVo = sRoleService.queryAllCurrDownOrgNotPage(sRoleVo);
                break;
            default:
                outputVo = sRoleService.queryAllOwnerNotPage(sRoleVo);
                break;
        }
        return getResponseData(outputVo);

    }

    private String getOrgLocations(List<String> locations){
        List<String> result = new ArrayList<>();
        if(Objects.isNull(locations) || locations.isEmpty()){
            return null;
        }
        for(String location : locations){
            if(StringUtil.isStrNotEmpty(location)){
                if(location.contains(",")){
                    String[] splits = location.split(",");
                    for(int i=0; i<splits.length; i++){
                        result.add(splits[i]);
                    }
                }else {
                    result.add(location);
                }

            }
        }
        if(result.size() > 0)
            return result.stream().distinct().collect(Collectors.joining(","));
        else
            return null;
    }

}
